package cn.pli.bike.ui;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.framemodule.base.BaseActivityPresenter;
import com.framemodule.base.netstatus.NetUtils;
import com.framemodule.utils.CommonUtils;

import cn.pli.bike.App;
import cn.pli.bike.R;
import cn.pli.bike.bean.HttpResult;
import cn.pli.bike.bean.UserBean;
import cn.pli.bike.model.UserModel;
import cn.pli.bike.model.http.ApiException;
import cn.pli.bike.model.subscribers.ProgramSubscriber;
import cn.pli.bike.url.API;
import cn.pli.bike.utils.AppUtils;

public class PhoneLogonActivity extends BaseActivityPresenter<PhoneLogonDelegate> implements View.OnClickListener {
    private boolean isPhone, isVerification, isVerificationEnable = true;
    private String phoneNum, verificationCode;
    ValueAnimator viewAnimator;

    @Override
    protected void initModel() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.setOnClickListener(this, R.id.iv_title_back, R.id.bt_send_verification, R.id.bt_commit, R.id.tv_user_agreement);
        viewDelegate.getEtPhone().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isPhone = s.toString().trim().length() == 11;
                updateButtonState();
            }
        });

        viewDelegate.getEtVerification().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isVerification = s.toString().trim().length() == 6;
                updateButtonState();

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                readyGoThenKill(MainActivity.class);
                finish();
                break;
            case R.id.bt_send_verification:
                phoneNum = viewDelegate.getEtPhone().getText().toString().trim();
                getVerification(phoneNum);
                break;
            case R.id.bt_commit:
                phoneNum = viewDelegate.getEtPhone().getText().toString().trim();
                verificationCode = viewDelegate.getEtVerification().getText().toString().trim();
                logon(phoneNum, verificationCode);
                break;
            case R.id.tv_user_agreement:
                Bundle bundle = new Bundle();
                bundle.putString("title", "用户注册协议");
                bundle.putString("url", API.URL.BASE_URL + "khBike.do?agreementDetial");
                readyGo(WebViewActivity.class, bundle);
                break;
        }

    }

    private void updateButtonState() {
        viewDelegate.getBtSendVerification().setEnabled(isPhone && isVerificationEnable);
        viewDelegate.getBtCommit().setEnabled(isPhone && isVerification);
    }

    private void startCountdown(int count) {
        isVerificationEnable = false;
        updateButtonState();
        viewAnimator = ValueAnimator.ofInt(count, 0);
        viewAnimator.setDuration(count * 1000);
        viewAnimator.setInterpolator(new LinearInterpolator());
        viewAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int i = (int) animation.getAnimatedValue();

                if (i == 0) {
                    isVerificationEnable = true;
                    viewDelegate.getBtSendVerification().setText(R.string.get_verification);
                    updateButtonState();
                } else {
                    viewDelegate.getBtSendVerification().setText(i + "s");
                }

            }
        });
        viewAnimator.start();
    }

    /**
     * 获取手机验证码
     *
     * @param phone
     */
    private void getVerification(String phone) {
        UserModel.postVerifyCode(new ProgramSubscriber<HttpResult<String>>() {
            @Override
            public void onNext(HttpResult<String> stringHttpResult) {
                viewDelegate.toast(stringHttpResult.getData());
                startCountdown(60);
            }

            @Override
            public void onErr(ApiException e) {
                super.onErr(e);
            }
        }, phone);
    }

    /**
     * 登录
     *
     * @param phone
     * @param verificationCode
     */
    private void logon(String phone, String verificationCode) {
        UserModel.postSignupOrLogin(new ProgramSubscriber<UserBean>() {
            @Override
            public void onNext(UserBean userBeanHttpResult) {
                AppUtils.saveUserInfo(userBeanHttpResult);
                // viewDelegate.toast(getString(R.string.logon_success));
                Bundle bundle = new Bundle();
                bundle.putString("type", "PhoneLogonActivity");
                bundle.putSerializable("userBean", userBeanHttpResult);
                readyGoThenKill(MainActivity.class, bundle);
                finish();
            }

            @Override
            public void onErr(ApiException e) {
                super.onErr(e);
                viewDelegate.toast(e.getMsg());
            }
        }, phone, verificationCode);
    }

    @Override
    public void finish() {
        if (viewAnimator != null) {
            if (viewAnimator.isRunning()) {
                viewAnimator.cancel();
            }
        }
        super.finish();
    }

    @Override
    public void onBackPressed() {
        readyGoThenKill(MainActivity.class);
        finish();
    }
}
